<template>
  <div class="login-container">
    <el-card class="login-box">
      <template #header>
        <div class="card-header">
          <h2>登录</h2>
          <el-tabs v-model="loginType" class="login-tabs">
            <el-tab-pane label="账号密码登录" name="account">
              <el-form
                ref="loginFormRef"
                :model="loginForm"
                :rules="rules"
                label-position="top"
                @submit.prevent="handleLogin"
              >
                <el-form-item prop="username" label="账号">
                  <el-input
                    v-model="loginForm.username"
                    placeholder="请输入手机号/邮箱"
                    :prefix-icon="User"
                  />
                </el-form-item>
                <el-form-item prop="password" label="密码">
                  <el-input
                    v-model="loginForm.password"
                    type="password"
                    placeholder="请输入密码"
                    :prefix-icon="Lock"
                    show-password
                  />
                </el-form-item>
                <div class="form-options">
                  <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                  <el-link type="primary" :underline="false">忘记密码？</el-link>
                </div>
                <el-button
                  type="primary"
                  native-type="submit"
                  :loading="isLoading"
                  class="submit-btn"
                >
                  {{ isLoading ? '登录中...' : '登录' }}
                </el-button>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="米哈游通行证" name="mihoyo">
              <div class="mihoyo-login">
                <el-button
                  type="default"
                  class="mihoyo-login-btn"
                  @click="handleMihoyoLogin"
                >
                  <el-image
                    src="/mihoyo-logo.png"
                    class="mihoyo-logo"
                    fit="contain"
                  />
                  使用米哈游通行证登录
                </el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>

      <div class="register-link">
        还没有账号？
        <el-link type="primary" :underline="false">
          <router-link to="/register">立即注册</router-link>
        </el-link>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { User, Lock } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { setToken, setUserInfo } from '@/utils/auth'

const router = useRouter()
const store = useStore()
const loginType = ref('account')
const rememberMe = ref(false)
const isLoading = ref(false)
const loginFormRef = ref<FormInstance>()

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
})

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    isLoading.value = true
    
    const response = await request.post('/user/user/login', {
      username: loginForm.username,
      password: loginForm.password
    })

    console.log('登录响应:', response)

    // 使用后端返回的 token
    setToken(response.data.token)
    
    // 获取用户详情
    const userDetailResponse = await request.get('/user/user/detail')
    console.log('用户详情响应:', userDetailResponse)
    
    // 使用后端返回的用户信息
    const userInfo = {
      id: response.data.id,
      username: response.data.username,
      avatar: userDetailResponse.data.image, // 使用用户详情中的图片
      email: response.data.email,
      phone: response.data.phone
    }
    setUserInfo(userInfo)
    store.dispatch('login', userInfo)
    
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error: any) {
    console.error('登录失败:', error)
    ElMessage.error(error.response?.data?.msg || '登录失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

const handleMihoyoLogin = () => {
  // TODO: 实现米哈游通行证登录
  window.location.href = 'https://passport.mihoyo.com/login'
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 80px);
  background-color: #f5f5f5;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 480px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 20px;
  color: #2c3e50;
  font-size: 24px;
}

.login-tabs {
  margin-bottom: 20px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.mihoyo-login {
  padding: 20px 0;
  text-align: center;
}

.mihoyo-login-btn {
  width: 100%;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.mihoyo-logo {
  width: 24px;
  height: 24px;
}

:deep(.el-tabs__nav) {
  width: 100%;
}

:deep(.el-tabs__item) {
  flex: 1;
  text-align: center;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style> 